package com.google.code.sip.ucenter.web.admin.controller;

import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.sip.ucenter.service.ApplicationManager;
import com.google.code.sip.ucenter.service.MongoManager;
import com.google.code.sip.ucenter.service.UserManager;

/**
 * 用户控制器
 * 
 * @author Liuye
 * 
 */
@Controller
public class IndexController {
	private static final Logger logger = LoggerFactory
			.getLogger(IndexController.class);
	@Autowired
	private UserManager userManager;
	@Autowired
	private ApplicationManager applicationManager;
	@Autowired
	private MongoManager mongoManager;

	@RequestMapping("/admin/index.do")
	public ModelAndView index() {
		return new ModelAndView("admin.index");
	}

	@RequestMapping("/admin/index!header.do")
	public ModelAndView header() {
		return new ModelAndView("admin.header");
	}

	@RequestMapping("/admin/index!menu.do")
	public ModelAndView menu() {
		return new ModelAndView("admin.menu");
	}

	@RequestMapping("/admin/index!workbench.do")
	public ModelAndView workbench() {
		ModelAndView modelAndView = new ModelAndView("admin.workbench");

		long userCount = userManager.countUser();
		long applicationCount = applicationManager.countApplication();
		Properties sysInfo = System.getProperties(); // 获得系统属性集
		modelAndView.addObject("userCount", userCount);
		modelAndView.addObject("applicationCount", applicationCount);
		// 获取操作系统信息
		modelAndView.addObject("sysInfo", sysInfo);
		modelAndView.addObject("totalMemory", Runtime.getRuntime()
				.totalMemory() / 1024 / 1024);
		modelAndView.addObject("maxMemory",
				Runtime.getRuntime().maxMemory() / 1024 / 1024);
		modelAndView.addObject("freeMemory",
				Runtime.getRuntime().freeMemory() / 1024 / 1024);
		modelAndView.addObject("availableProcessors", Runtime.getRuntime()
				.availableProcessors());
		// 获取数据库信息
		modelAndView.addObject("mongoInfo", mongoManager.getMongoInfo());
		return modelAndView;
	}

	@RequestMapping("/admin/index!forceGC.do")
	public ModelAndView forceGC(HttpServletRequest request,
			HttpServletResponse response) {
		boolean finalization = ServletRequestUtils.getBooleanParameter(request,
				"fin", false);
		if (finalization) {
			Runtime.getRuntime().runFinalization();
			logger.debug("Advised finalization");
		} else {
			Runtime.getRuntime().gc();
			logger.debug("Advised Garbage Collection");
		}
		return new ModelAndView("admin.index");
	}
}
